<template>
  <div class="driver-approval-container">
    <el-card class="driver-approval-card">
      <template #header>
        <div class="card-header">
          <span>司机申请审批</span>
        </div>
      </template>

      <el-table
        :data="driverApplications"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="real_name" label="真实姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <span>{{ scope.row.gender}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="driver_license" label="驾驶证号" width="180" />
        <el-table-column label="申请时间" width="180">
          <template #default="scope">
            <span>{{ formatDate(scope.row.register_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="approveApplication(scope.row)"
              :loading="scope.row.approving"
            >
              批准
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="rejectApplication(scope.row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 拒绝原因对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝申请"
      width="500px"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因:">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            placeholder="请输入拒绝原因"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button
            type="danger"
            @click="confirmReject"
            :loading="rejecting"
          >
            确认拒绝
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '@/api/user_api.js'

// 数据相关
const driverApplications = ref([])
const loading = ref(false)
const rejectDialogVisible = ref(false)
const rejecting = ref(false)

// 拒绝表单
const rejectForm = ref({
  userId: null,
  reason: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}

// 获取司机申请列表
const fetchDriverApplications = async () => {
  loading.value = true
  try {
    // 调用API获取状态为1(申请待审批)的用户列表
    const res = await userApi.getDriverApplications()

    if (res && Array.isArray(res)) {
      driverApplications.value = res
      total.value = res.length
    } else {
      driverApplications.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取司机申请列表失败: ' + (error.message || '未知错误'))
    driverApplications.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 批准申请
const approveApplication = (application) => {
  ElMessageBox.confirm(
    `确定要批准用户 ${application.username} 的司机申请吗？`,
    '确认批准',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 设置正在批准状态
      application.approving = true

      // 调用API批准申请
      const res = await userApi.approveDriverApplication(application.id)

      if (res) {
        ElMessage.success('司机申请已批准')
        // 更新本地数据
        // application.driver_apply_status = 2
        // 重新获取列表
        await fetchDriverApplications()
        // 关闭对话框
        //dialogVisible.value = false
      } else {
        ElMessage.error('批准失败')
      }
    } catch (error) {
      ElMessage.error('批准失败: ' + (error.message || '未知错误'))
    } finally {
      application.approving = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 显示拒绝对话框
const rejectApplication = (application) => {
  rejectForm.value.userId = application.id
  rejectForm.value.reason = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  rejecting.value = true
  try {
    // 调用API拒绝申请
    const res = await userApi.rejectDriverApplication(
      rejectForm.value.userId,
      rejectForm.value.reason
    )

    if (res) {
      ElMessage.success('司机申请已拒绝')
      rejectDialogVisible.value = false
      // 重新获取列表
      await fetchDriverApplications()
    } else {
      ElMessage.error('拒绝失败')
    }
  } catch (error) {
    ElMessage.error('拒绝失败: ' + (error.message || '未知错误'))
  } finally {
    rejecting.value = false
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDriverApplications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDriverApplications()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDriverApplications()
})
</script>

<style scoped>
.driver-approval-container {
  padding: 20px;
  background-color: #f7f9fc;
  min-height: 100%;
}

.driver-approval-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
